<template>
  <view class="advanceOrder">
    <!--主体内容-->
    <view class="advanceOrder-content">
      <!--场馆信息-->
      <MyCard :is-radius="false" class="mb-4">
        <view class="flex items-center justify-between">
          <view>
            <view class="font-bold text-xs mb-2">场馆信息</view>
            <view class="font-bold text-xs mb-1">
              {{ projectDetails.bkiSiteSelect }} （{{ convertToHoursMinute(projectDetails.bkiStartTime) }} -
              {{ convertToHoursMinute(projectDetails.bkiEndTime) }}）
            </view>
            <view class="text-gray-500 text-xs mt-1 line-clamp-2">中国车谷国际体育文化交流中心</view>
          </view>
          <view class="flex items-center justify-between">
            <view class="text-xs" @tap="toLocationPlace(projectDetails.bkiVenue)">
              <text class="material-icons text-amber-300 mr-8">location_on</text>
              <view>地图</view>
            </view>
            <view class="text-xs" @tap="makeCall(projectDetails.bkiPhone)">
              <text class="material-icons text-emerald-500">call</text>
              <view>电话</view>
            </view>
          </view>
        </view>
      </MyCard>

      <!-- 车位信息-->
      <MyCard :is-radius="false" class="mb-4">
        <view class="font-bold mb-2">车位信息</view>
        <template v-if="parkingList.length">
          <view v-for="(item, index) in parkingList" :key="index">
            <u-cell
              :title="`车辆${index + 1}`"
              :value="item"
              isLink
              size="large"
              @click="talkingAboutLicensePlateTable"
            />
          </view>
        </template>
        <view v-else class="flex items-center justify-center parking-content flex-col">
          <u-image height="100" src="@/static/image/parking-reservation.png" width="150" />
          <view class="text-xl font-bold mb-2">您是否提前预约车位</view>
          <view class="flex">
            <u-button plain shape="circle" text="暂时不用" type="primary" />
            <u-button
              custom-style="margin-left:16rpx"
              plain
              shape="circle"
              text="立即预约"
              type="primary"
              @click="talkingAboutLicensePlateTable"
            />
          </view>
        </view>
      </MyCard>

      <!--车位信息弹出层-->
      <u-modal
        ref="uModal"
        :show="show"
        negative-top="20"
        showCancelButton
        title="车位信息"
        @cancel="closePopup"
        @confirm="confirm"
      >
        <view class="popup-content mt-6 w-full">
          <view class="flex items-center justify-between sticky top-0 bg-white z-[99999]">
            <text class="font-bold">选择预定车位数量</text>
            <u-number-box v-model="comParkingSpaceQuantitySize" :min="0" integer @change="updateParkingSpaceQuantity" />
          </view>
          <view v-for="(item, index) in parkingSpaceQuantity" :key="index">
            <view class="text-blue-400 font-bold mb-2 mt-2">车辆{{ index + 1 }}</view>
            <view class="flex items-center">
              <car-number-input
                :defaultStr="item"
                class="flex-1"
                @numberInputResult="numberInputResult($event, index)"
              />
              <text class="material-icons text-red-500" @click="deleteNumberInput(index)">cancel</text>
            </view>
          </view>
        </view>
      </u-modal>

      <!-- 场地信息-->
      <MyCard :is-radius="false" class="mb-4">
        <view class="font-bold mb-2">车位信息</view>
        <u-cell
          v-for="(item, index) in userBookingSiteBos.sysOrderItemBoList"
          :key="index"
          :value="`￥${item.itemProductPrice / 100}元`"
          class="cell-details"
        >
          <template #title>
            <text class="text-blue-600 font-bold text-xs">场次{{ index + 1 }}</text>
            <view class="text-stone-500 mt-2 mb-2">{{ item.itemProductName }}</view>
            <text v-for="(item, idx) in transformationData(item.itemNote)" :key="idx" class="font-bold">
              {{ item.value }}
            </text>
          </template>
        </u-cell>
      </MyCard>

      <!-- 支付-->
      <MyCard :is-radius="false" class="mb-4 pt-20">
        <u-radio-group v-model="paymentNum" iconPlacement="right" placement="column">
          <view v-for="(item, index) in TYPE_OF_PAYMENT" :key="index" class="flex items-center">
            <u-image :src="item.image" height="30" width="30" />
            <u-radio
              :customStyle="{ padding: '10px', flex: 1 }"
              :label="item.name"
              :name="item.status"
              class="flex-1"
            />
          </view>
        </u-radio-group>
      </MyCard>
    </view>

    <!--注释-->
    <view class="pay-desk">
      <view>
        共选中
        <text class="text-red-500">{{ userBookingSiteBos.sysOrderItemBoList.length }}</text>
        场，合计：
        <text class="text-red-500">￥{{ priceSum }}</text>
      </view>
      <u-button :custom-style="{ width: '180rpx' }" shape="circle" type="primary" @click="payment">支付</u-button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import MyCard from '@/components/MyCard/MyCard.vue';
import { PLACE_POINT, TYPE_OF_PAYMENT } from '@/constants/base';
import { makeCall, toLocation } from '@/utils/common';
import { useSubscribeStore } from '@/stores/subscribe';
import { convertToHoursMinute } from '@/utils/date';
import { PLAY } from '@/api/play';
import useHttpRepositories from '@/composables/useHttpRepositories';
import currency from 'currency.js';
import { SUBSCRIBE } from '@/api/subscribe';
import { clone } from 'xe-utils';

const { $http } = useHttpRepositories();
const { projectDetails, userBookingSiteBos, parkingSpaceInfo } = storeToRefs(useSubscribeStore());
const { setParkingSpaceInfo, setUserBookingSiteBos } = useSubscribeStore();

const parkingSpaceQuantity = ref([]); // 车位数据

// 车位数量
const comParkingSpaceQuantitySize = computed(() => parkingSpaceQuantity.value.length);

const numberInputResult = (val, index) => {
  parkingSpaceQuantity.value[index] = val;
};

// 精确删除车位
const deleteNumberInput = (index) => {
  parkingSpaceQuantity.value.splice(index, 1);
  console.log(parkingSpaceQuantity.value);
};

const show = ref(false); // 弹出层
const parkingList = ref([]);

// 弹出车位信息弹出层
const talkingAboutLicensePlateTable = () => {
  // 显示弹框
  show.value = true;
  if (parkingList.value.length === 0) {
    parkingSpaceQuantity.value.push('');
  } else {
    parkingSpaceQuantity.value = clone(parkingList.value, true);
  }
};

// 改变车位数量
const updateParkingSpaceQuantity = (params) => {
  // 如果车牌号和数量相等就不执行了
  if (params.value === comParkingSpaceQuantitySize.value) return;
  // 代表新增车牌号
  if (params.value > comParkingSpaceQuantitySize.value) {
    // 拿到需要生成的数量
    const sum = params.value - comParkingSpaceQuantitySize.value;
    // 拿到数量填充很多个初始化对象
    const array = new Array(sum).fill('');
    // 新增对象
    parkingSpaceQuantity.value.push(...array);
  } else {
    // 拿到需要生成的数量
    const sum = comParkingSpaceQuantitySize.value - params.value;

    // 减去需要删除的对象
    parkingSpaceQuantity.value.splice(params.value, sum);
  }
};

// 确定
const confirm = () => {
  // 判断是否有空值车位
  const isParking = parkingSpaceQuantity.value.filter(Boolean);
  console.log(isParking);
  if (parkingSpaceQuantity.value.length !== isParking.length) {
    uni.$u.toast('车位号不能为空');
    return;
  }

  // 判断是否有少输入车位号的车位
  const isCorrectLicensePlate = parkingSpaceQuantity.value.filter((parkNum) => parkNum.trim().length >= 7);
  if (parkingSpaceQuantity.value.length !== isCorrectLicensePlate.length) {
    uni.$u.toast('有车位号输入错误，请检查再提交');
    return;
  }

  // 不能提交重复的车位号
  const setParkingSpaceQuantity = [...new Set(parkingSpaceQuantity.value)];
  if (parkingSpaceQuantity.value.length !== setParkingSpaceQuantity.length) {
    uni.$u.toast('不能提交重复的车位号');
    return;
  }

  $http.post({
    url: SUBSCRIBE.UPDATE_CAR_INFO,
    data: {
      bkiCarNo: parkingSpaceQuantity.value.toString(),
      bkiCarNum: parkingSpaceQuantity.value.length,
      userBookingSiteBos: userBookingSiteBos.value.sysOrderItemBoList.map((item) => ({ id: item.itemProductId }))
    },
    success: () => {
      const cloneParkingSpace = clone(parkingSpaceQuantity.value, true);

      // 存入pina
      setParkingSpaceInfo(cloneParkingSpace);

      // 赋值展示数据变量
      parkingList.value = clone(cloneParkingSpace);

      // 关闭弹框
      closePopup();
    }
  });
};

//

// 关闭弹框
const closePopup = () => {
  show.value = false;
  parkingSpaceQuantity.value = [];
};

// 选择支付
const paymentNum = ref(0);

// 场馆导航
const toLocationPlace = (name) => {
  toLocation({
    name, // 位置名字
    latitude: PLACE_POINT[name].lat, // 维度
    longitude: PLACE_POINT[name].lng, // 经度
    address: name // 地址详细说明
  }).then(() => {
    console.log('成功');
  });
};

// json转换数据
const transformationData = (json) => {
  return JSON.parse(json || '[]');
};

const priceSum = computed(() => {
  return userBookingSiteBos.value.sysOrderItemBoList.reduce((pro, cur) => {
    pro = currency(pro).add(cur.itemProductPrice / 100);
    return pro;
  }, 0);
});

// 开始支付
const payment = () => {
  if (paymentNum.value !== 0) {
    uni.$u.toast('暂不支持，请使用微信支付');
    return;
  }

  $http.get({
    url: `${PLAY.WECHAT_XCX_PLAY}${userBookingSiteBos.value.orderNo}`,
    success: (res) => {
      const sussess = () => {
        uni.$u.toast('支付成功');
        uni.$u.route({
          type: 'reLaunch',
          url: '/pages/order/index'
        });

        // 清空上一次数据
        setParkingSpaceInfo({});
        setUserBookingSiteBos({});
      };
      if (res === null) {
        sussess();
      } else {
        uni.requestPayment({
          orderInfo: '',
          provider: 'wxpay',
          timeStamp: res.timeStamp,
          nonceStr: res.nonceStr,
          package: res.prepayId,
          signType: res.signType,
          paySign: res.paySign,
          success: sussess,
          fail: () => {
            uni.$u.toast('支付失败，请重新支付');
          }
        });
      }
    }
  });
};

onReady(() => {
  // 初始化赋值车位信息
  parkingList.value = clone(parkingSpaceInfo.value, true);
});
</script>

<style lang="scss" scoped>
.parking-content {
  background-color: rgb(250, 250, 251);
}

.advanceOrder {
  height: 100vh;

  .advanceOrder-content {
    height: calc(100% - 160rpx);
    overflow: auto;

    :deep(.cell-details) {
      .u-cell__body {
        align-items: flex-end;
      }
    }

    .popup-content {
      max-height: 600rpx;
      min-height: 400rpx;
      overflow: auto;
    }
  }

  .pay-desk {
    @apply h-20 font-bold bg-white flex items-center justify-between p-5 fixed bottom-0 left-0 w-full shadow-neutral-600 shadow-2xl;
  }
}
</style>
